package site.xuxingcan.wifihost;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.SystemClock;
import android.provider.Settings;
import android.support.v7.app.AppCompatActivity;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;

public class MainActivity extends AppCompatActivity {
    // Content View Elements

    private LinearLayout mActivity_main;
    private EditText mAp_name;
    private EditText mAp_key;
    private Button mYidong;
    private Button mLiantong;
    private Button mUpdate;
    private Button mClear;
    private TextView mLine_text;
    private ImageView mWifi_icon;
    private Button mRefresh;
    private Button mShare;
    private TextView mMsg;

    // End Of Content View Elements

    private void bindViews() {

        mActivity_main = (LinearLayout) findViewById(R.id.activity_main);
        mAp_name = (EditText) findViewById(R.id.ap_name);
        mAp_key = (EditText) findViewById(R.id.ap_key);
        mYidong = (Button) findViewById(R.id.yidong);
        mLiantong = (Button) findViewById(R.id.liantong);
        mUpdate = (Button) findViewById(R.id.update);
        mClear = (Button) findViewById(R.id.clear);
        mLine_text = (TextView) findViewById(R.id.line_text);
        mWifi_icon = (ImageView) findViewById(R.id.wifi_icon);
        mRefresh = (Button) findViewById(R.id.refresh);
        mShare = (Button) findViewById(R.id.share);
        mMsg = (TextView) findViewById(R.id.msg);
    }


    private WifiManager wifiManager;
    private Handler mHandler;
    private Context mContext;
    private int checkNetWorkTimes = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        bindViews();
        mContext = this;
        mHandler = new Handler(Looper.getMainLooper());
        mClear.setOnClickListener(listener);
        mYidong.setOnClickListener(listener);
        mLiantong.setOnClickListener(listener);
        mUpdate.setOnClickListener(listener);
        mRefresh.setOnClickListener(listener);
        mShare.setOnClickListener(listener);
        wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
        mAp_name.setText(SharedPreferenceUtil.getInstance(this).getWifiName());
        mAp_key.setText(SharedPreferenceUtil.getInstance(this).getWifiKey());
        File textFile = new File(mContext.getDir("zip", Context.MODE_PRIVATE), "说明文字.txt");
        if (textFile.exists()) {
            try {
                String text = FileUtil.readMsgFile(textFile);
                mMsg.setText(text);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        startService(new Intent(this, NotifyService.class));
    }

    public boolean isWifiApEnabled() {
        return getWifiApState() == 3;
    }

    private int getWifiApState() {
        int tmp;
        try {
            Method method = wifiManager.getClass().getMethod("getWifiApState");
            tmp = ((Integer) method.invoke(wifiManager));
            // Fix for Android 4
            if (tmp > 10) {
                tmp = tmp - 10;
            }
            return tmp;
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return 0;
        }
    }

    // wifi热点开关
    public boolean setWifiApEnabled(boolean enabled) {
        String apkey = mAp_key.getText().toString();
        if (TextUtils.isEmpty(apkey) || apkey.length() < 10) {
            DialogHelper.showMessageDialog(mContext, "警告", "密码长度太短", null);
            return false;
        }
        String apname = mAp_name.getText().toString();
        if (TextUtils.isEmpty(apname) || apname.length() < 5) {
            DialogHelper.showMessageDialog(mContext, "信息", "WIFI名称太短", null);
            return false;
        }
        SharedPreferenceUtil.getInstance(this).setWifiKey(apkey);
        SharedPreferenceUtil.getInstance(this).setWifiName(apname);
        if (enabled) {
            //wifi和热点不能同时打开，所以打开热点的时候需要关闭wifi
            wifiManager.setWifiEnabled(false);
        }
        try {
            Method method = wifiManager.getClass().getMethod("setWifiApEnabled", WifiConfiguration.class, Boolean.TYPE);
            method.invoke(wifiManager, null, false);
            //热点的配置类
            WifiConfiguration mWifiConfig = new WifiConfiguration();
            mWifiConfig.SSID = apname;
            mWifiConfig.preSharedKey = apkey;
            mWifiConfig.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
            mWifiConfig.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
            mWifiConfig.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
            mWifiConfig.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
            mWifiConfig.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
            mWifiConfig.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
            mWifiConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
            mWifiConfig.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
            return (Boolean) method.invoke(wifiManager, mWifiConfig, enabled);
        } catch (Exception e) {
            return false;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        checkClickTime();
        checkWifi();
        refreshWifiButton();
    }

    private void refreshWifiButton() {
        switch (SharedPreferenceUtil.getInstance(mContext).getWifiButton()) {
            case 0:
                mShare.setEnabled(true);
                mRefresh.setEnabled(true);
                break;
            case 1:
                mShare.setEnabled(true);
                mRefresh.setEnabled(false);
                break;
            case 2:
                mShare.setEnabled(false);
                mRefresh.setEnabled(true);
                break;
        }
    }

    private void checkWifi() {
        if (isWifiApEnabled()) {
            mWifi_icon.setImageResource(R.mipmap.wifi_on);
            mShare.setText("重启热点");
            mRefresh.setText("重启热点");
        } else {
            mWifi_icon.setImageResource(R.mipmap.wifi_off);
            mShare.setText("开启热点");
            mRefresh.setText("刷新热点");
        }
    }

    private void checkClickTime() {
        long bootTime = System.currentTimeMillis() - SystemClock.elapsedRealtime();
        long lastClickTime = SharedPreferenceUtil.getInstance(this).getLastClickTime();
        if (bootTime < lastClickTime) {
            mYidong.setEnabled(false);
            mLiantong.setEnabled(false);
        } else {
            mYidong.setEnabled(true);
            mLiantong.setEnabled(true);
        }
        mLine_text.setText("上次使用：" + SharedPreferenceUtil.getInstance(mContext).getLineString());
    }

    private AlertDialog updateMsgDialog;
    private AlertDialog msgDialog;
    private View.OnClickListener listener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (isShowFirstDialog()) {
                return;
            }
            File zipDir = mContext.getDir("zip", Context.MODE_PRIVATE);
            switch (v.getId()) {
                case R.id.yidong:
                    File yidongFile = new File(zipDir, "移动文件");
                    if (!yidongFile.exists()) {
                        DialogHelper.showMessageDialog(mContext, "警告", "没有可用的线路，请更新服务器后再试！", null);
                        return;
                    }
                    final HashMap<String, Integer> yidongMap = new HashMap<>();
                    for (int i = 1; i <= 5; i++) {
                        File f = new File(yidongFile, i + "");
                        if (f.exists()) {
                            yidongMap.put("线路" + i, i);
                        }
                    }
                    if (yidongMap.size() == 0) {
                        DialogHelper.showMessageDialog(mContext, "警告", "没有可用的线路，请更新服务器后再试！", null);
                        return;
                    }
                    final String[] yidongItems = new String[yidongMap.size()];
                    int yi = 0;
                    for (HashMap.Entry<String, Integer> entry : yidongMap.entrySet()) {
                        yidongItems[yi] = entry.getKey();
                        yi++;
                    }
                    DialogHelper.showMenuDialog(mContext, "请选择线路", yidongItems, new DialogHelper.MenuDialogCallBack() {
                        @Override
                        public void onItemOnClick(DialogInterface dialog, int which) {
                            int line = yidongMap.get(yidongItems[which]);
                            execYidongLine(line);
                        }
                    });
                    break;
                case R.id.liantong:
                    File liantongFile = new File(zipDir, "联通文件");
                    if (!liantongFile.exists()) {
                        DialogHelper.showMessageDialog(mContext, "警告", "没有可用的线路，请更新服务器后再试！", null);
                        return;
                    }
                    final HashMap<String, Integer> liantongmap = new HashMap<>();
                    for (int i = 1; i <= 5; i++) {
                        File f = new File(liantongFile, i + "");
                        if (f.exists()) {
                            liantongmap.put("线路" + i, i);
                        }
                    }
                    if (liantongmap.size() == 0) {
                        DialogHelper.showMessageDialog(mContext, "警告", "没有可用的线路，请更新服务器后再试！", null);
                        return;
                    }
                    final String[] items = new String[liantongmap.size()];
                    int lian = 0;
                    for (HashMap.Entry<String, Integer> entry : liantongmap.entrySet()) {
                        items[lian] = entry.getKey();
                        lian++;
                    }
                    DialogHelper.showMenuDialog(mContext, "请选择线路", items, new DialogHelper.MenuDialogCallBack() {
                        @Override
                        public void onItemOnClick(DialogInterface dialog, int which) {
                            int line = liantongmap.get(items[which]);
                            execLiantongLine(line);
                        }
                    });
                    break;
                case R.id.update:
                    AlertDialog.Builder builder = new AlertDialog.Builder(mContext);  //先得到构造器
                    builder.setTitle("更新"); //设置标题
                    builder.setMessage("请链接可以正常上网的WIFI后进行更新，设备本身网络不支持更新！"); //设置内容
                    builder.setPositiveButton("更新", new DialogInterface.OnClickListener() { //设置确定按钮
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            update(false);
                        }
                    });
                    builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });
                    builder.setNeutralButton("其他", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            DialogHelper.showEditTextDialog(mContext, "信息", "请输入密码", new DialogHelper.DialogCallBack() {
                                @Override
                                public void onConfirm(DialogInterface dialog, String s) {
                                    if ("qaz123".equalsIgnoreCase(s)) {
                                        update(true);
                                    } else {
                                        DialogHelper.showMessageDialog(mContext, "信息", "密码错误", null);
                                    }
                                }

                                @Override
                                public void onCancel(DialogInterface dialog) {

                                }
                            });
                        }
                    });
                    builder.setCancelable(false);
                    builder.create().show();
                    break;
                case R.id.share:
                    checkNetWorkTimes = 0;
                    msgDialog = DialogHelper.showOnlyMessageDialog(MainActivity.this, "信息", "开启中......");
                    checkNetWork();
                    break;
                case R.id.refresh:
                    msgDialog = DialogHelper.showOnlyMessageDialog(MainActivity.this, "信息", "刷新中......");
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                File dir = mContext.getDir("zip", Context.MODE_PRIVATE);
                                File timeFile = new File(dir, "时间.txt");
                                String s = FileUtil.readFileSdcardFile(timeFile);
                                long time = Integer.parseInt(s.split("/")[0]) * 1000;
                                exec(SharedPreferenceUtil.getInstance(mContext).getQuanxianPath());
                                execInService(SharedPreferenceUtil.getInstance(mContext).getRefreshPath());
                                Thread.sleep(time);
                                exec(SharedPreferenceUtil.getInstance(mContext).getQuanxianPath());
                                execInService(SharedPreferenceUtil.getInstance(mContext).getRefreshPath());
                                Thread.sleep(time);
                                mHandler.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        if (msgDialog != null) {
                                            msgDialog.dismiss();
                                        }
                                        if (setWifiApEnabled(true)) {
                                            DialogHelper.showMessageDialog(mContext, "信息", "刷新成功", null);
                                        } else {
                                            DialogHelper.showMessageDialog(mContext, "信息", "刷新失败", null);
                                        }
                                    }
                                });
                            } catch (Exception e) {
                                e.printStackTrace();
                                mHandler.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        if (msgDialog != null) {
                                            msgDialog.dismiss();
                                        }
                                        DialogHelper.showMessageDialog(mContext, "信息", "刷新失败", null);
                                    }
                                });
                            }
                        }
                    }).start();
                    break;
                case R.id.clear:
                    SharedPreferenceUtil.getInstance(mContext).setLastClickTime(0);
                    checkClickTime();
                    break;
            }
        }
    };

    private void execLiantongLine(final int line) {
        msgDialog = DialogHelper.showOnlyMessageDialog(MainActivity.this, "信息", "执行中......");
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String quanxian = "";
                    File dir = mContext.getDir("zip", Context.MODE_PRIVATE);
                    String shell = "mount -o remount rw /system\n";
                    String liantongApnPath = FileUtil.readFileSdcardFile(new File(dir, "联通APN路径.txt"));
                    String liantongApn = new File(dir, "联通APN").getAbsolutePath();
                    shell += "cp -rf " + liantongApn + "/* " + liantongApnPath + "\n";

                    String liantongPath = FileUtil.readFileSdcardFile(new File(dir, "联通路径.txt"));
                    File liantongFiles = new File(dir, "联通文件/" + line);
                    shell += "cp -rf " + liantongFiles.getAbsolutePath() + "/* " + liantongPath + "\n";

                    File liantongBeifenFile = new File(dir, "联通备份路径.txt");
                    File liantongBeifenFiles = new File(dir, "联通备份文件");
                    if (liantongBeifenFile.exists() && liantongBeifenFiles.exists()) {
                        String yidongBeifenPath = FileUtil.readFileSdcardFile(liantongBeifenFile);
                        shell += "cp -rf " + liantongBeifenFiles.getAbsolutePath() + "/* " + yidongBeifenPath + "\n";
                    }

                    File liantongBeifenPathFile1 = new File(dir, "联通备用1路径.txt");
                    File liantongBeifenFiles1 = new File(dir, "联通备用文件1");
                    File liantongBeifenFilesQuanxianFile1 = new File(dir, "联通备用1权限.txt");
                    if (liantongBeifenPathFile1.exists() && liantongBeifenFiles1.exists()) {
                        String liantongBeifenPath1 = FileUtil.readFileSdcardFile(liantongBeifenPathFile1);
                        shell += "cp -rf " + liantongBeifenFiles1.getAbsolutePath() + "/* " + liantongBeifenPath1 + "\n";
                        if (liantongBeifenFilesQuanxianFile1.exists()) {
                            String liantongBeifenFilesQuanxian1 = FileUtil.readFileSdcardFile(liantongBeifenFilesQuanxianFile1);
                            for (File f : liantongBeifenFiles1.listFiles()) {
                                File newf = new File(liantongBeifenPath1, f.getName());
                                shell += "chmod -R " + liantongBeifenFilesQuanxian1 + " " + newf.getAbsolutePath() + "\n";
                                quanxian += "chmod -R " + liantongBeifenFilesQuanxian1 + " " + newf.getAbsolutePath() + "\n";
                            }
                        }
                    }

                    File liantongBeifenPathFile2 = new File(dir, "联通备用2路径.txt");
                    File liantongBeifenFiles2 = new File(dir, "联通备用文件2");
                    File liantongBeifenFilesQuanxianFile2 = new File(dir, "联通备用2权限.txt");
                    if (liantongBeifenPathFile2.exists() && liantongBeifenFiles2.exists()) {
                        String liantongBeifenPath2 = FileUtil.readFileSdcardFile(liantongBeifenPathFile2);
                        shell += "cp -rf " + liantongBeifenFiles2.getAbsolutePath() + "/* " + liantongBeifenPath2 + "\n";
                        if (liantongBeifenFilesQuanxianFile2.exists()) {
                            String liantongBeifenFilesQuanxian2 = FileUtil.readFileSdcardFile(liantongBeifenFilesQuanxianFile2);
                            for (File f : liantongBeifenFiles2.listFiles()) {
                                File newf = new File(liantongBeifenPath2, f.getName());
                                shell += "chmod -R " + liantongBeifenFilesQuanxian2 + " " + newf.getAbsolutePath() + "\n";
                                quanxian += "chmod -R " + liantongBeifenFilesQuanxian2 + " " + newf.getAbsolutePath() + "\n";
                            }
                        }
                    }

                    String liantongQuanXian = FileUtil.readFileSdcardFile(new File(dir, "联通文件权限.txt"));
                    for (File f : liantongFiles.listFiles()) {
                        File newf = new File(liantongPath, f.getName());
                        shell += "chmod -R " + liantongQuanXian + " " + newf.getAbsolutePath() + "\n";
                        quanxian += "chmod -R " + liantongQuanXian + " " + newf.getAbsolutePath() + "\n";
                    }

                    File liantongQuanxianFile = new File(mContext.getDir("shell", MODE_PRIVATE), "liantongQuanxian");
                    if (liantongQuanxianFile.exists()) {
                        liantongQuanxianFile.delete();
                    }
                    FileUtil.writeFileSdcardFile(liantongQuanxianFile, quanxian);
                    SharedPreferenceUtil.getInstance(mContext).setQuanxianPath("sh " + liantongQuanxianFile.getAbsolutePath());

                    File liantongShellFile = new File(mContext.getDir("shell", MODE_PRIVATE), "liantongShell");
                    if (liantongShellFile.exists()) {
                        liantongShellFile.delete();
                    }
                    FileUtil.writeFileSdcardFile(liantongShellFile, shell);
                    exec("sh " + liantongShellFile.getAbsolutePath());

                    String liantongExe = FileUtil.readMsgFile(new File(dir, "联通执行.txt"));
                    execInService("sh " + liantongExe + " &");
                    SharedPreferenceUtil.getInstance(mContext).setRefreshPath("sh " + liantongExe + " &");
                    SharedPreferenceUtil.getInstance(mContext).setLastClickTime(System.currentTimeMillis());
                    SharedPreferenceUtil.getInstance(mContext).setLineStringh("模式2 线路" + line);
                    final String button = FileUtil.readMsgFile(new File(dir, "联通按钮.txt"));
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            checkClickTime();
                            if (msgDialog != null) {
                                msgDialog.dismiss();
                            }
                            SharedPreferenceUtil.getInstance(mContext).setWifiButton(0);
                            if (!TextUtils.isEmpty(button)) {
                                if (button.contains("开启热点")) {
                                    SharedPreferenceUtil.getInstance(mContext).setWifiButton(1);
                                } else if (button.contains("刷新热点")) {
                                    SharedPreferenceUtil.getInstance(mContext).setWifiButton(2);
                                }
                            }
                            refreshWifiButton();
                            DialogHelper.showMessageDialog(mContext, "信息", "执行完毕", null);
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                    SharedPreferenceUtil.getInstance(mContext).setLineStringh("无");
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            checkClickTime();
                            if (msgDialog != null) {
                                msgDialog.dismiss();
                            }
                            DialogHelper.showMessageDialog(mContext, "信息", "执行失败", null);
                        }
                    });
                }
            }
        }).start();
    }

    private void execYidongLine(final int line) {
        msgDialog = DialogHelper.showOnlyMessageDialog(MainActivity.this, "信息", "执行中......");
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    File dir = mContext.getDir("zip", Context.MODE_PRIVATE);
                    String shell = "mount -o remount rw /system\n";
                    String quanxian = "";
                    String yidongApnPath = FileUtil.readFileSdcardFile(new File(dir, "移动APN路径.txt"));
                    String yidongApn = new File(dir, "移动APN").getAbsolutePath();
                    shell += "cp -rf " + yidongApn + "/* " + yidongApnPath + "\n";

                    String yidongPath = FileUtil.readFileSdcardFile(new File(dir, "移动路径.txt"));
                    File yidongFiles = new File(dir, "移动文件/" + line);
                    shell += "cp -rf " + yidongFiles.getAbsolutePath() + "/* " + yidongPath + "\n";

                    File yidongBeifenPathFile1 = new File(dir, "移动备用1路径.txt");
                    File yidongBeifenFiles1 = new File(dir, "移动备用文件1");
                    File yidongBeifenFilesQuanxianFile1 = new File(dir, "移动备用1权限.txt");
                    if (yidongBeifenPathFile1.exists() && yidongBeifenFiles1.exists()) {
                        String yidongBeifenPath1 = FileUtil.readFileSdcardFile(yidongBeifenPathFile1);
                        shell += "cp -rf " + yidongBeifenFiles1.getAbsolutePath() + "/* " + yidongBeifenPath1 + "\n";
                        if (yidongBeifenFilesQuanxianFile1.exists()) {
                            String yidongBeifenFilesQuanxian1 = FileUtil.readFileSdcardFile(yidongBeifenFilesQuanxianFile1);
                            for (File f : yidongBeifenFiles1.listFiles()) {
                                File newf = new File(yidongBeifenPath1, f.getName());
                                shell += "chmod -R " + yidongBeifenFilesQuanxian1 + " " + newf.getAbsolutePath() + "\n";
                                quanxian += "chmod -R " + yidongBeifenFilesQuanxian1 + " " + newf.getAbsolutePath() + "\n";
                            }
                        }
                    }

                    File yidongBeifenPathFile2 = new File(dir, "移动备用2路径.txt");
                    File yidongBeifenFiles2 = new File(dir, "移动备用文件2");
                    File yidongBeifenFilesQuanxianFile2 = new File(dir, "移动备用2权限.txt");
                    if (yidongBeifenPathFile2.exists() && yidongBeifenFiles2.exists()) {
                        String yidongBeifenPath2 = FileUtil.readFileSdcardFile(yidongBeifenPathFile2);
                        shell += "cp -rf " + yidongBeifenFiles2.getAbsolutePath() + "/* " + yidongBeifenPath2 + "\n";
                        if (yidongBeifenFilesQuanxianFile2.exists()) {
                            String yidongBeifenFilesQuanxian2 = FileUtil.readFileSdcardFile(yidongBeifenFilesQuanxianFile2);
                            for (File f : yidongBeifenFiles2.listFiles()) {
                                File newf = new File(yidongBeifenPath2, f.getName());
                                shell += "chmod -R " + yidongBeifenFilesQuanxian2 + " " + newf.getAbsolutePath() + "\n";
                                quanxian += "chmod -R " + yidongBeifenFilesQuanxian2 + " " + newf.getAbsolutePath() + "\n";
                            }
                        }
                    }

                    String yidongQuanXian = FileUtil.readFileSdcardFile(new File(dir, "移动文件权限.txt"));
                    for (File f : yidongFiles.listFiles()) {
                        File newf = new File(yidongPath, f.getName());
                        shell += "chmod -R " + yidongQuanXian + " " + newf.getAbsolutePath() + "\n";
                        quanxian += "chmod -R " + yidongQuanXian + " " + newf.getAbsolutePath() + "\n";
                    }

                    File yidongQuanxianFile = new File(mContext.getDir("shell", MODE_PRIVATE), "yidongQuanxian");
                    if (yidongQuanxianFile.exists()) {
                        yidongQuanxianFile.delete();
                    }
                    FileUtil.writeFileSdcardFile(yidongQuanxianFile, quanxian);
                    SharedPreferenceUtil.getInstance(mContext).setQuanxianPath("sh " + yidongQuanxianFile.getAbsolutePath());

                    File yidongShellFile = new File(mContext.getDir("shell", MODE_PRIVATE), "yidongShell");
                    if (yidongShellFile.exists()) {
                        yidongShellFile.delete();
                    }
                    FileUtil.writeFileSdcardFile(yidongShellFile, shell);
                    exec("sh " + yidongShellFile.getAbsolutePath());

                    String yidongExe = FileUtil.readMsgFile(new File(dir, "移动执行.txt"));
                    execInService("sh " + yidongExe + " &");
                    SharedPreferenceUtil.getInstance(mContext).setRefreshPath("sh " + yidongExe + " &");
                    SharedPreferenceUtil.getInstance(mContext).setLastClickTime(System.currentTimeMillis());
                    SharedPreferenceUtil.getInstance(mContext).setLineStringh("模式1 线路" + line);
                    final String button = FileUtil.readMsgFile(new File(dir, "移动按钮.txt"));
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            checkClickTime();
                            if (msgDialog != null) {
                                msgDialog.dismiss();
                            }
                            SharedPreferenceUtil.getInstance(mContext).setWifiButton(0);
                            if (!TextUtils.isEmpty(button)) {
                                if (button.contains("开启热点")) {
                                    SharedPreferenceUtil.getInstance(mContext).setWifiButton(1);
                                } else if (button.contains("刷新热点")) {
                                    SharedPreferenceUtil.getInstance(mContext).setWifiButton(2);
                                }
                            }
                            refreshWifiButton();
                            DialogHelper.showMessageDialog(mContext, "信息", "执行完毕", null);
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                    SharedPreferenceUtil.getInstance(mContext).setLineStringh("无");
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            checkClickTime();
                            if (msgDialog != null) {
                                msgDialog.dismiss();
                            }
                            DialogHelper.showMessageDialog(mContext, "信息", "执行失败", null);
                        }
                    });
                }
            }
        }).start();
    }

    private void execInService(String cmd) {
        Intent intent = new Intent(this, NotifyService.class);
        intent.putExtra("CMD", cmd);
        startService(intent);
    }

    private void update(final boolean isOther) {
        updateMsgDialog = DialogHelper.showOnlyMessageDialog(MainActivity.this, "信息", "更新中......");
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
                    String imei = telephonyManager.getDeviceId();
                    if (TextUtils.isEmpty(imei)) {
                        mHandler.post(new Runnable() {
                            @Override
                            public void run() {
                                if (updateMsgDialog != null) {
                                    updateMsgDialog.dismiss();
                                }
                                DialogHelper.showMessageDialog(mContext, "警告", "无法获取imei，请授予权限后再试！", null);
                            }
                        });
                        return;
                    }
                    String _urlStr = "http://120.25.216.222:8090/WCDMA200?key=" + imei;
                    if (isOther) {
                        _urlStr = "http://120.25.216.222:8090/WCDMA201?key=" + imei;
                    }
                    File file = new File(Environment.getExternalStorageDirectory(), "wifi_host_all_config.zip");
                    URL url = new URL(_urlStr);
                    URLConnection con = url.openConnection();
                    InputStream is = con.getInputStream();
                    byte[] bs = new byte[1024];
                    int len;
                    OutputStream os = new FileOutputStream(file);
                    while ((len = is.read(bs)) != -1) {
                        os.write(bs, 0, len);
                    }
                    os.close();
                    is.close();
                    String dir = mContext.getDir("zip", Context.MODE_PRIVATE).getAbsolutePath();
                    execWaitFor("rm -rf " + dir + "/*");
                    ZipUtil.unzip(file, mContext.getDir("zip", Context.MODE_PRIVATE));
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            if (updateMsgDialog != null) {
                                updateMsgDialog.dismiss();
                            }
                            DialogHelper.showMessageDialog(mContext, "信息", "更新成功", new DialogHelper.DialogCallBack() {
                                @Override
                                public void onConfirm(DialogInterface dialog, String s) {
                                    try {
                                        exec("reboot");
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                }

                                @Override
                                public void onCancel(DialogInterface dialog) {

                                }
                            });
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            if (updateMsgDialog != null) {
                                updateMsgDialog.dismiss();
                            }
                            DialogHelper.showMessageDialog(mContext, "信息", "更新失败", null);
                        }
                    });
                }
            }
        }).start();
    }

    public void setAirplaneMode(boolean enable) {
        try {
            Settings.System.putInt(mContext.getContentResolver(), Settings.System.AIRPLANE_MODE_ON, enable ? 1 : 0);
            Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
            intent.putExtra("state", enable);
            mContext.sendBroadcast(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            exec("am broadcast -a android.intent.action.AIRPLANE_MODE --ez state " + enable + ";");
        } catch (Exception e1) {
            e1.printStackTrace();
        }
    }

    public void checkNetWork() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                setWifiApEnabled(false);
                HttpURLConnection conn = null;
                File dir = mContext.getDir("zip", Context.MODE_PRIVATE);
                File timeFile = new File(dir, "时间.txt");
                long time = 20 * 1000;
                if (timeFile.exists()) {
                    try {
                        String s = FileUtil.readFileSdcardFile(timeFile);
                        time = Integer.parseInt(s.split("/")[1]) * 1000;
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                try {
                    Thread.sleep(20 * 1000);
                    URL url = new URL("http://www.baidu.com");
                    conn = (HttpURLConnection) url.openConnection();
                    conn.setRequestMethod("GET");
                    conn.setDoOutput(true);
                    conn.setConnectTimeout(10 * 1000);
                    conn.setReadTimeout(10 * 1000);
                    conn.connect();
                    BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                    StringBuilder sb = new StringBuilder();
                    String readLine;
                    while ((readLine = in.readLine()) != null) {
                        sb.append(readLine).append("\n");
                    }
                    in.close();
                    final String result = sb.toString();
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            if (setWifiApEnabled(true)) {
                                mHandler.postDelayed(new Runnable() {
                                    @Override
                                    public void run() {
                                        if (msgDialog != null) {
                                            msgDialog.dismiss();
                                        }
                                        checkWifi();
                                        DialogHelper.showMessageDialog(mContext, "信息", "开启成功", null);
                                    }
                                }, 10000);
                            }
//                            if (result.contains("百度")) {
//                                DialogHelper.showMessageDialog(mContext, "信息", "开启成功", null);
//                            } else {
//                                if (checkNetWorkTimes == 0) {
//                                    checkNetWorkTimes = 1;
//                                    msgDialog = DialogHelper.showOnlyMessageDialog(MainActivity.this, "信息", "开启中......");
//                                    setAirplaneMode(true);
//                                    mHandler.postDelayed(new Runnable() {
//                                        @Override
//                                        public void run() {
//                                            setAirplaneMode(false);
//                                        }
//                                    }, 10000);
//                                    mHandler.postDelayed(new Runnable() {
//                                        @Override
//                                        public void run() {
//                                            checkNetWork();
//                                        }
//                                    }, 20000);
//                                } else {
//                                    DialogHelper.showMessageDialog(mContext, "信息", "开启失败", null);
//                                }
//                            }
                        }
                    });
                } catch (Exception e) {
                    final long finalTime = time;
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            if (msgDialog != null) {
                                msgDialog.dismiss();
                            }
                            if (checkNetWorkTimes == 0) {
                                checkNetWorkTimes = 1;
                                msgDialog = DialogHelper.showOnlyMessageDialog(MainActivity.this, "信息", "开启中......");
                                setAirplaneMode(true);
                                mHandler.postDelayed(new Runnable() {
                                    @Override
                                    public void run() {
                                        setAirplaneMode(false);
                                    }
                                }, finalTime);
                                mHandler.postDelayed(new Runnable() {
                                    @Override
                                    public void run() {
                                        checkNetWork();
                                    }
                                }, finalTime * 2);
                            } else {
                                checkWifi();
                                DialogHelper.showMessageDialog(mContext, "信息", "开启失败", null);
                            }
                        }
                    });
                } finally {
                    try {
                        if (conn != null) {
                            conn.disconnect();
                        }
                    } catch (Exception e) {
                    }
                }
            }
        }).start();
    }

    private boolean isShowFirstDialog() {
        if (SharedPreferenceUtil.getInstance(this).getIsShowFirstDialog()) {
            DialogHelper.showEditTextDialog(this, "信息", "请输入密码", new DialogHelper.DialogCallBack() {
                public AlertDialog msgDialog;

                @Override
                public void onConfirm(DialogInterface dialog, final String s) {
                    dialog.dismiss();
                    msgDialog = DialogHelper.showOnlyMessageDialog(MainActivity.this, "信息", "上传中......");
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
                                String imei = telephonyManager.getDeviceId();
                                if (TextUtils.isEmpty(imei)) {
                                    mHandler.post(new Runnable() {
                                        @Override
                                        public void run() {
                                            if (msgDialog != null) {
                                                msgDialog.dismiss();
                                            }
                                            DialogHelper.showMessageDialog(mContext, "警告", "无法获取imei，请授予权限后再试！", null);
                                        }
                                    });
                                    return;
                                }
                                URL url = new URL("http://120.25.216.222:8090/?key=" + imei + "&pwd=" + s);
                                url.openConnection();
                                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                                conn.setConnectTimeout(20 * 1000);
                                conn.setReadTimeout(20 * 1000);
                                InputStreamReader is = new InputStreamReader(conn.getInputStream());
                                BufferedReader bufferedReader = new BufferedReader(is);
                                StringBuffer strBuffer = new StringBuffer();
                                String line = null;
                                while ((line = bufferedReader.readLine()) != null) {
                                    strBuffer.append(line);
                                }
                                String result = strBuffer.toString();
                                if (result.equalsIgnoreCase("success")) {
                                    mHandler.post(new Runnable() {
                                        @Override
                                        public void run() {
                                            SharedPreferenceUtil.getInstance(MainActivity.this).setIsShowFirstDialog(false);
                                            if (msgDialog != null) {
                                                msgDialog.dismiss();
                                            }
                                            DialogHelper.showMessageDialog(MainActivity.this, "信息", "设备校验成功", null);
                                        }
                                    });
                                } else {
                                    mHandler.post(new Runnable() {
                                        @Override
                                        public void run() {
                                            if (msgDialog != null) {
                                                msgDialog.dismiss();
                                            }
                                            DialogHelper.showMessageDialog(MainActivity.this, "信息", "设备校验失败", null);
                                        }
                                    });
                                }
                                is.close();
                                conn.disconnect();
                            } catch (Exception e) {
                                e.printStackTrace();
                                mHandler.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        if (msgDialog != null) {
                                            msgDialog.dismiss();
                                        }
                                        DialogHelper.showMessageDialog(MainActivity.this, "信息", "设备校验失败", null);
                                    }
                                });
                            }
                        }
                    }).start();
                }

                @Override
                public void onCancel(DialogInterface dialog) {

                }
            });
            return true;
        } else {
            return false;
        }
    }

    private void copyBigDataToSD(Context mContext, String name, String strOutFileName) throws Exception {
        InputStream myInput;
        OutputStream myOutput = new FileOutputStream(strOutFileName);
        myInput = mContext.getAssets().open(name);
        byte[] buffer = new byte[1024];
        int length = myInput.read(buffer);
        while (length > 0) {
            myOutput.write(buffer, 0, length);
            length = myInput.read(buffer);
        }
        myOutput.flush();
        myInput.close();
        myOutput.close();
    }

    public static void exec(String paramString) throws Exception {
        Process localProcess = Runtime.getRuntime().exec("su");
        DataOutputStream localDataOutputStream = new DataOutputStream(localProcess.getOutputStream());
        localDataOutputStream.writeBytes(paramString + "\n");
//        localDataOutputStream.writeBytes("exit\n");
        localDataOutputStream.flush();
//        localDataOutputStream.close();
//        localProcess.waitFor();
//        localProcess.destroy();
    }

    public static void execWaitFor(String paramString) throws Exception {
        Process localProcess = Runtime.getRuntime().exec("su");
        DataOutputStream localDataOutputStream = new DataOutputStream(localProcess.getOutputStream());
        localDataOutputStream.writeBytes(paramString + "\n");
        localDataOutputStream.writeBytes("exit\n");
        localDataOutputStream.flush();
        localDataOutputStream.close();
        localProcess.waitFor();
        localProcess.destroy();
    }
}
